package com.dreamfly.qiyeweixinrobot.utils;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;

/**
 * @description: 图片处理
 * @author: DreamflyChen
 * @create: 2020-08-29 23:05
 */
@Slf4j
public class ImageManager {
    /**
     * @Description 图片转base64字符串
     * @param imgUrl 图片路径(Resources目录下, 如/img/pic1.png)
     * @return
     */
    public static String imageToBase64Str(String imgUrl) {
        InputStream inputStream;
        byte[] data;
        try {
            inputStream = ImageManager.class.getResourceAsStream(imgUrl);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            log.error("图片转base64字符串异常, 异常信息如下:{}", e.getMessage());
            return null;
        }
        // 加密
        BASE64Encoder encoder = new BASE64Encoder();
        //去掉换行符
        String result = encoder.encode(data).replaceAll("\r|\n", "");
        return result;
    }

    /**
     * @Description 生成文件的md5值
     * @param fileUrl 文件路径(Resources目录下, 如/img/pic1.png)
     * @return MD5值
     */
    public static String getStringMd5(String fileUrl) throws Exception {
        String value;
        //toURI() 解决中文路径乱码问题
        String path = ImageManager.class.getResource(fileUrl).toURI().getPath();
        try (FileInputStream in = new FileInputStream(path)) {
            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, new File(path).length());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(byteBuffer);
            BigInteger bi = new BigInteger(1, md5.digest());
            value = bi.toString(16);
        }
        return value;
    }
}
